﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KeaoBase;
using GoldPrinter;
using System.Diagnostics;

namespace KeaoMDS.Report
{
    public partial class TuiKuRiQiHuiZong : BaseForm
    {
        private string m_ChengZhongLeiXing = string.Empty;

        public TuiKuRiQiHuiZong(string ChengZhongLeiXing)
        {
            m_ChengZhongLeiXing = ChengZhongLeiXing;
            InitializeComponent();
        }

        private void TuiKuHuiZong_Load(object sender, EventArgs e)
        {
            grid_riqi.AutoGenerateColumns = false;
            this.MinimumSize = this.Size;
            dateTimePicker1.Value = DateTime.Today;
            dateTimePicker2.Value = dateTimePicker1.Value.AddHours(23).AddMinutes(59).AddSeconds(59);

            BindWuLiao();
            BindInfo();
            this.Text = string.Format("{0}{1}", m_ChengZhongLeiXing, this.Text);
        }

        private void BindWuLiao()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("wuliaoleixing", DataValueCommonType.字符串, m_ChengZhongLeiXing, "", SearchConditionType.等于);
            createCondition += KeaoUtils._DB.CreateAndCondition("wuliaozhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_wuliao", createCondition);
            DataRow newRow = Dt.NewRow();
            newRow["wuliaomingcheng"] = "—请选择—";
            newRow["id"] = "";
            Dt.Rows.InsertAt(newRow, 0);
            cmb_wuliao.DisplayMember = "wuliaomingcheng";
            cmb_wuliao.ValueMember = "id";
            cmb_wuliao.DataSource = Dt;
        }

        private void cmb_wuliao_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmb_wuliao.SelectedIndex != 0)
            {
                BindXingHao();
            }
            else
            {
                cmb_xinghao.DataSource = null;
            }
        }

        private void BindXingHao()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("wuliaobianhao", DataValueCommonType.字符串, cmb_wuliao.SelectedValue.ToString(), "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_xinghao", createCondition);
            DataRow newRow = Dt.NewRow();
            newRow["xinghao"] = "—请选择—";
            newRow["id"] = "";
            Dt.Rows.InsertAt(newRow, 0);
            cmb_xinghao.DisplayMember = "xinghao";
            cmb_xinghao.ValueMember = "id";
            cmb_xinghao.DataSource = Dt;
        }

        private void BindInfo()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("tuikushijian", DataValueCommonType.日期时间, dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss"), dateTimePicker2.Value.ToString("yyyy-MM-dd HH:mm:ss"), SearchConditionType.between);
            if (cmb_wuliao.SelectedIndex > 0)
            {
                createCondition += KeaoUtils._DB.CreateAndCondition("tuikuwuliao", DataValueCommonType.字符串, cmb_wuliao.Text, "", SearchConditionType.等于);
            }
            if (cmb_xinghao.SelectedIndex > 0)
            {
                createCondition += KeaoUtils._DB.CreateAndCondition("tuikuxinghao", DataValueCommonType.字符串, cmb_xinghao.Text, "", SearchConditionType.等于);
            }
            createCondition += KeaoUtils._DB.CreateAndCondition("tuikuleixing", DataValueCommonType.字符串, m_ChengZhongLeiXing, "", SearchConditionType.等于);
            string tableCols = string.Empty;
            string groupCols = string.Empty;
            Dictionary<string, string> orderBy = new Dictionary<string, string>();
            orderBy.Add("tuikuwuliao", "asc");
            orderBy.Add("tuikuxinghao", "asc");

            tableCols = string.Format("{0} as riqi,tuikuwuliao,tuikuxinghao,count(id) as cheshu,sum(tuikumaozhong) as tuikumaozhong,sum(tuikupizhong) as tuikupizhong,sum(tuikujingzhong) as tuikujingzhong", KeaoUtils._DB.DateFormatFun("tuikushijian"));
            groupCols = string.Format("{0},tuikuwuliao,tuikuxinghao", KeaoUtils._DB.DateFormatFun("tuikushijian"));
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", tableCols, null, createCondition, groupCols, orderBy);

            tableCols = string.Format("tuikuwuliao,tuikuxinghao,count(id) as cheshu,sum(tuikumaozhong) as tuikumaozhong,sum(tuikupizhong) as tuikupizhong,sum(tuikujingzhong) as tuikujingzhong");
            groupCols = string.Format("tuikuwuliao,tuikuxinghao");
            DataTable DtCount = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", tableCols, null, createCondition, groupCols, orderBy);

            tableCols = string.Format("count(id) as cheshu,sum(tuikumaozhong) as tuikumaozhong,sum(tuikupizhong) as tuikupizhong,sum(tuikujingzhong) as tuikujingzhong");
            DataTable DtCountAll = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", tableCols, null, createCondition, null, orderBy);

            if (Dt.Rows.Count > 0)
            {
                for (int i = 0; i < Dt.Rows.Count; i++)
                {
                    if (i == Dt.Rows.Count - 1)
                    {
                        DataRow newRow = Dt.NewRow();
                        newRow["tuikuxinghao"] = "合计：";
                        newRow["cheshu"] = DtCount.Rows[0]["cheshu"];
                        newRow["tuikumaozhong"] = DtCount.Rows[0]["tuikumaozhong"];
                        newRow["tuikupizhong"] = DtCount.Rows[0]["tuikupizhong"];
                        newRow["tuikujingzhong"] = DtCount.Rows[0]["tuikujingzhong"];
                        Dt.Rows.InsertAt(newRow, i + 1);
                        DtCount.Rows.RemoveAt(0);
                        i++;
                        break;
                    }
                    if (!Dt.Rows[i]["tuikuwuliao"].Equals(Dt.Rows[i + 1]["tuikuwuliao"]) || !Dt.Rows[i]["tuikuxinghao"].Equals(Dt.Rows[i + 1]["tuikuxinghao"]))
                    {
                        DataRow newRow = Dt.NewRow();
                        newRow["tuikuxinghao"] = "合计：";
                        newRow["cheshu"] = DtCount.Rows[0]["cheshu"];
                        newRow["tuikumaozhong"] = DtCount.Rows[0]["tuikumaozhong"];
                        newRow["tuikupizhong"] = DtCount.Rows[0]["tuikupizhong"];
                        newRow["tuikujingzhong"] = DtCount.Rows[0]["tuikujingzhong"];
                        Dt.Rows.InsertAt(newRow, i + 1);
                        DtCount.Rows.RemoveAt(0);
                        i++;
                    }
                }

                DataRow countAllRow = Dt.NewRow();
                countAllRow["tuikuxinghao"] = "总计：";
                countAllRow["cheshu"] = DtCountAll.Rows[0]["cheshu"];
                countAllRow["tuikumaozhong"] = DtCountAll.Rows[0]["tuikumaozhong"];
                countAllRow["tuikupizhong"] = DtCountAll.Rows[0]["tuikupizhong"];
                countAllRow["tuikujingzhong"] = DtCountAll.Rows[0]["tuikujingzhong"];
                Dt.Rows.Add(countAllRow);
            }
            grid_riqi.DataSource = Dt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            BindInfo();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DataTable Dt = grid_riqi.DataSource as DataTable;
            if (Dt == null)
            {
                return;
            }
            //报表导出
            if (m_ChengZhongLeiXing == "入库物料")
            {
                ExcelAccess excelAccess = new ExcelAccess();
                try
                {
                    excelAccess.Open(Application.StartupPath + "\\Template\\入库物资退库日期汇总报表.xls");
                    excelAccess.SetCellText(2, "A", string.Format("报表时间：{0}——{1}", dateTimePicker1.Value, dateTimePicker2.Value));
                    for (int i = 0; i < Dt.Rows.Count; i++)
                    {
                        excelAccess.SetCellText(i + 4, "A", string.Format("{0}", Dt.Rows[i]["riqi"]));
                        excelAccess.SetCellText(i + 4, "B", string.Format("{0}", Dt.Rows[i]["tuikuwuliao"]));
                        excelAccess.SetCellText(i + 4, "C", string.Format("{0}", Dt.Rows[i]["tuikuxinghao"]));
                        excelAccess.SetCellText(i + 4, "D", string.Format("{0}", Dt.Rows[i]["cheshu"]));
                        excelAccess.SetCellText(i + 4, "E", string.Format("{0}", Dt.Rows[i]["tuikujingzhong"]));
                    }

                    excelAccess.MergeCells(4 + Dt.Rows.Count, "A", 4 + Dt.Rows.Count, "E", true);
                    excelAccess.SetCellText(4 + Dt.Rows.Count, "A", string.Format("制表人：{0}    制表时间：{1}", KeaoUtils._CurrentUserRow["yonghuxingming"], DateTime.Now.ToString("yyyy-MM-dd HH:mm")));

                    Excel.Range r = excelAccess.GetRange(4, "A", Dt.Rows.Count + 3, "E");
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlLeft);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlRight);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlBottom);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlInsideHorizontal);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlInsideVertical);

                    FolderBrowserDialog fbd = new FolderBrowserDialog();
                    if (fbd.ShowDialog() == DialogResult.OK)
                    {
                        excelAccess.SaveAs(string.Format("{0}\\{1}.xls", fbd.SelectedPath, DateTime.Now.ToString("yyyyMMddHHmm")), true);
                        KeaoUtils.ShowInfoMessage("报表导出Excel成功。");
                        Process.Start(fbd.SelectedPath);
                    }

                }
                catch (Exception err)
                {
                    KeaoUtils.LogTxt(string.Format("入库物资退库日期汇总报表导出失败。{0}", err.Message));
                }
                finally
                {
                    excelAccess.Close();
                }
            }
            else
            {
                ExcelAccess excelAccess = new ExcelAccess();
                try
                {
                    excelAccess.Open(Application.StartupPath + "\\Template\\出库物资退库日期汇总报表.xls");
                    excelAccess.SetCellText(2, "A", string.Format("报表时间：{0}——{1}", dateTimePicker1.Value, dateTimePicker2.Value));
                    for (int i = 0; i < Dt.Rows.Count; i++)
                    {
                        excelAccess.SetCellText(i + 4, "A", string.Format("{0}", Dt.Rows[i]["riqi"]));
                        excelAccess.SetCellText(i + 4, "B", string.Format("{0}", Dt.Rows[i]["tuikuwuliao"]));
                        excelAccess.SetCellText(i + 4, "C", string.Format("{0}", Dt.Rows[i]["tuikuxinghao"]));
                        excelAccess.SetCellText(i + 4, "D", string.Format("{0}", Dt.Rows[i]["cheshu"]));
                        excelAccess.SetCellText(i + 4, "E", string.Format("{0}", Dt.Rows[i]["tuikujingzhong"]));
                    }

                    excelAccess.MergeCells(4 + Dt.Rows.Count, "A", 4 + Dt.Rows.Count, "E", true);
                    excelAccess.SetCellText(4 + Dt.Rows.Count, "A", string.Format("制表人：{0}    制表时间：{1}", KeaoUtils._CurrentUserRow["yonghuxingming"], DateTime.Now.ToString("yyyy-MM-dd HH:mm")));

                    Excel.Range r = excelAccess.GetRange(4, "A", Dt.Rows.Count + 3, "E");
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlLeft);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlRight);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlBottom);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlInsideHorizontal);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlInsideVertical);

                    FolderBrowserDialog fbd = new FolderBrowserDialog();
                    if (fbd.ShowDialog() == DialogResult.OK)
                    {
                        excelAccess.SaveAs(string.Format("{0}\\{1}.xls", fbd.SelectedPath, DateTime.Now.ToString("yyyyMMddHHmm")), true);
                        KeaoUtils.ShowInfoMessage("报表导出Excel成功。");
                        Process.Start(fbd.SelectedPath);
                    }

                }
                catch (Exception err)
                {
                    KeaoUtils.LogTxt(string.Format("出库物资退库日期汇总报表导出失败。{0}", err.Message));
                }
                finally
                {
                    excelAccess.Close();
                }
            }
        }


    }
}
